using System;
using System.Configuration;
using System.Diagnostics;
using System.Xml;

namespace SimpleAppStart
{
	/// <summary>
	/// Implements IConfigurationSectionHandler.  Creates an AppStartConfig object which encapsulates necessary configuration settings
	/// in a strong-typed reliable class for consumption by AppStart core process.
	/// </summary>
	internal class ConfigSectionHandler : IConfigurationSectionHandler
	{
		#region Constructors

		/// <summary>
		/// Default constructor.
		/// </summary>
		public ConfigSectionHandler()
		{
		}

		#endregion

		#region IConfigurationSectionHandler members


		/// <summary>
		/// This class is responsible for reading the configuration and creating an instance of the configuration class.
		/// 
		/// &lt;ClientApplicationInfo&gt;
		/// &lt;appFolderName&gt;C:\temp\pag\AppUpdaterClient&lt;/appFolderName&gt;
		/// &lt;appExeName&gt;SampleApplicationForBitsDownload.exe&lt;/appExeName&gt;
		/// &lt;/ClientApplicationInfo&gt;
		/// </summary>
		/// <param name="parent"></param>
		/// <param name="configContext"></param>
		/// <param name="section"></param>
		/// <returns></returns>
		object IConfigurationSectionHandler.Create( object parent, object configContext, XmlNode section )
		{
			AppStartConfiguration config = null;
			XmlNode rootNode = null;
			XmlNode subNode = null;
			string temp = "";

			//  grab an instance of AppStartConfiguration
			config = new AppStartConfiguration();

			//  get the primary node "ClientApplicationInfo" so we can access others easily
			rootNode = section.SelectSingleNode("ClientApplicationInfo");

			//  access each subnode, validating values and adding them to our instance of config object			
			try
			{
				subNode = rootNode.SelectSingleNode("appFolderName");
				if ( null != subNode )
				{
					temp = subNode.InnerText;
					//  check if terminal slash, add if missing
					if ( !temp.EndsWith( @"\" ) )
					{
						temp += @"\";
					}
					config.FolderName = temp;
				}
			
				subNode = rootNode.SelectSingleNode("appExeName");
				if ( null != subNode )
				{
					config.ExecutableName = subNode.InnerText;
				}

				subNode = rootNode.SelectSingleNode( "appID" );
				if ( null != subNode )
				{
					temp = subNode.InnerText;
					config.ApplicationID = subNode.InnerText;
				}

				subNode = rootNode.SelectSingleNode( "updateTime" );
				if ( subNode != null )
				{
					config.UpdateTime = (UpdateTimeEnum)Enum.Parse( typeof( UpdateTimeEnum ), subNode.InnerText );
				}

				subNode = rootNode.SelectSingleNode( "manifestUri" );
			{
				config.ManifestUri = new Uri( subNode.InnerText );
			}

			}
			catch( Exception e )
			{
				Trace.WriteLine( "AppStart:[ConfigSectionHandler.Create]: Error during parsing of app.config file:" + Environment.NewLine + e.Message );
				throw e;
			}

			return config;

		}
		#endregion
	}
}
